//
//  TTJobChosedViewController.m
//  togetherPlay
//
//  Created by Mac on 2018/12/21.
//  Copyright © 2018 stoneobs.qq.com. All rights reserved.
//

#import "THCategoryHomeViewController.h"
#import "THCategoryControl.h"
#import "THCagetoryModel.h"
#import "THCategoryDataController.h"
@interface THCategoryHomeViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSMutableArray                    *dataSouce;/**<  */
@property(nonatomic, strong) NSMutableArray                     *controlArray;/**<  */
@property(nonatomic, strong) THCateModel                     *chosedModel;/**< 选中的第一级模型 */
@property(nonatomic, strong) NSMutableArray                     *goldArray;/**<  */

@property(nonatomic, strong) STButton                     *messageButton;/**<  */
@property(nonatomic, strong) STButton                     *button;/**<  */

@property(nonatomic, strong) STTools_TagMenuView                     *menuView;/**<  */
@end

@implementation THCategoryHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self send_all_cate_list_request];

    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.dataSouce.count == 0) {
        [self send_all_cate_list_request];
    }
    
}
- (void)reloadData{
    [self configSubView];
}
- (void)configMenuView{
    CGFloat qianyi = 0;
    if (self.rt_navigationController.childViewControllers.count > 1) {
        qianyi = 49;
    }
    CGFloat buttonWith = UISCREEN_WIDTH / 7;
    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, buttonWith, TMUtils.stoneobs_fun_get_tabBarTop+qianyi -TMUtils.stoneobs_fun_get_navgationBarBootom)];
    scrollView.backgroundColor = WH_UICOLOR_FROM_RGBA(0xF6F6F6);
    [self.view addSubview:scrollView];
    NSArray * array = [self.dataSouce stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
    if (self.selected_name.length) {
        THCateModel * nowmodel ;
        for (THCateModel * model in self.dataSouce) {
            if ([self.selected_name isEqualToString:model.name]) {
                nowmodel = model;
            }
        }
        self.dataSouce = nowmodel.subs.mutableCopy;
        array = [self.dataSouce stoneobs_fun_arrayFromObjKeyName:@"obj.name"];;
        self.chosedModel = nowmodel;
    }
    self.controlArray = [NSMutableArray new];
    __weak typeof(self) weakSelf =  self;
    for (NSInteger i = 0; i < array.count; i ++) {
        NSString * title = array[i];
        THCategoryControl * control = [[THCategoryControl alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 55) title:title];
        [scrollView addSubview:control];
        [control setOnSelectedControl:^(THCategoryControl *sender) {
            for (THCategoryControl * existControl in self.controlArray) {
                existControl.selected = NO;
                sender.selected = YES;
                
            }
            THCateModel * model = weakSelf.dataSouce[i];
            weakSelf.chosedModel = model;
            [weakSelf config_seg_view];
        }];
        control.top = i * control.height;
        [self.controlArray addObject:control];
        if (i == 0) {
            control.selected = YES;
            THCateModel * model = weakSelf.dataSouce.firstObject;
            weakSelf.chosedModel = model;
            [weakSelf config_seg_view];
        }
        scrollView.contentSize = CGSizeMake(0, control.bottom);
    }
    
}

- (void)configSubView{
    CGFloat qianyi = 0;
    if (self.rt_navigationController.childViewControllers.count > 1) {
        qianyi = 49;
    }
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_navgationBarBootom)];
    topView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topView];
    [topView stoneobs_fun_st_showBottomLine];
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(UISCREEN_WIDTH / 7, topView.bottom + 0, UISCREEN_WIDTH - UISCREEN_WIDTH / 7, TMUtils.stoneobs_fun_get_tabBarTop+qianyi - topView.bottom - 0);
    self.tableView.showsVerticalScrollIndicator = NO;
    
    if (qianyi > 0) {
        self.title = @"分类";
    }else{
        self.navigationController.navigationBar.hidden = YES;
        self.title = @"分类";
        __weak typeof(self) weakSelf =  self;
        STButton * messageButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                             title:nil
                                                        titleColor:nil
                                                         titleFont:0
                                                      cornerRadius:0
                                                   backgroundColor:nil
                                                   backgroundImage:nil
                                                             image:[UIImage imageNamed:@"good_搜索"]];
        [topView addSubview:messageButton];
        [messageButton setClicAction:^(UIButton *sender) {
            [TMUtils goto_search_controller];
        }];
        messageButton.right = UISCREEN_WIDTH;
        //    messageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [topView addSubview:messageButton];
        [messageButton setClicAction:^(UIButton *sender) {
            [TMUtils goto_search_controller];
        }];
        messageButton.bottom = topView.height;
        
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, 200, 44)
                                                                text:@"分类"
                                                           textColor:UIColor.blackColor
                                                                font:20
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        stoneobs_ui_label.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:20];
        [topView addSubview:stoneobs_ui_label];
        stoneobs_ui_label.bottom = topView.height;
    }
    
    [self configMenuView];
    
    
}
- (void)config_seg_view{
//    if (self.selected_name.length) {
//        [self configTableHeaderView];
//        return;
//    }
//    [self.menuView removeFromSuperview];
//
//    __weak typeof(self) weakSelf =  self;
//    NSArray * array = [self.chosedModel.subs stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
//    if (array.count == 0) {
//        self.tableView.tableHeaderView = UIView.new;
//        [self.tableView reloadData];
//        return;;
//    }
//    UIScrollView * stoneobs_ui_scroll_view = [[UIScrollView alloc] initWithFrame:CGRectMake(0 + self.tableView.left,TMUtils.stoneobs_fun_get_navgationBarBootom + 5, self.tableView.width - 10, 35)];
//    if (@available(iOS 11.0, *)) {
//        stoneobs_ui_scroll_view.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    } else {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
//    [self.view addSubview:stoneobs_ui_scroll_view];
//    STTools_TagMenuView * main_menuView = [STTools_TagMenuView.alloc initWithFrame:CGRectMake(0 + 0,5, self.tableView.width - 10, 20)];
//    main_menuView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//    main_menuView.forceButtonHeight = 24;
//    main_menuView.cornerRadius = 12;
//
//    main_menuView.buttonBackGroundColor = UIColor.clearColor;
//    main_menuView.buttonSelctedBackGroundColor = WH_UICOLOR_FROM_RGBA(0xD8FFE5);
//
//    main_menuView.butTitleColor = WH_UICOLOR_FROM_RGBA(0x9A9A9A);
//    main_menuView.butTitleSelectedColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
//
//    main_menuView.buttonBoderColor = UIColor.clearColor;
//    main_menuView.buttonSelectedBoderColor = UIColor.clearColor;
//    main_menuView.contentHorizontalAlignment = STTools_TagMenuViewDirection_stoneobs_enumHorizontal;
//    NSArray * marray = array;
//    main_menuView.allArray = marray;
//    main_menuView.chosedArray = @[marray.firstObject];
//    [main_menuView setOnSlectedTagView:^(STTools_TagMenuView *tagView, NSString *title, NSInteger index) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [weakSelf configTableHeaderView];
//        });
//
//    }];
//    self.menuView = main_menuView;
//    [stoneobs_ui_scroll_view addSubview:main_menuView];
//    stoneobs_ui_scroll_view.contentSize = CGSizeMake(main_menuView.right+10, 0);
//    main_menuView.chosedArray = @[array.firstObject];
    [self configTableHeaderView];
    
}
- (void)configTableHeaderView{
    __weak typeof(self) weakSelf =  self;
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 0.1)];
    self.tableView.backgroundColor = UIColor.whiteColor;
    CGFloat top = 10;
    THCateModel * model;
    
    CGFloat buttonWith = self.tableView.width /3;
    THCateModel * emodel = self.chosedModel.subs.firstObject;
//    如果三级没有数据，证明是其他地方进去的分类
    if (emodel.subs.count == 0) {
        CGFloat temptop = top;
        for (NSInteger i = 0; i < self.chosedModel.subs.count; i ++) {
            THCateModel * subModel = self.chosedModel.subs[i];
            STTools_MenuControl * menuControl = [[STTools_MenuControl alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 130) imageName:@"" title:subModel.name titleColor:STONEOBS_UI_FIRST_TEXT_COLOR imageHeight:80 lableHeight:40];
            [menuControl setOnSelctedControl:^(STTools_MenuControl *control) {
                
                THCateDetailViewController * vc = THCateDetailViewController.new;
                vc.c_id = subModel.c_id;
                [weakSelf pushViewController:vc animated:1];
            }];
            menuControl.top = temptop + menuControl.height * (i/3);
            menuControl.left = buttonWith * (i%3);
            header.height = menuControl.bottom;
            [menuControl.imageButton sd_setImageWithURL:subModel.icon.mj_url forState:UIControlStateNormal];;
            [header addSubview:menuControl];
            top = menuControl.bottom;
            
        }
    }else{
        for (NSInteger i = 0; i < self.chosedModel.subs.count; i ++) {
            THCateModel * model = self.chosedModel.subs[i];
            STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, top, header.width, 40)
                                                                    text:model.name
                                                               textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                                    font:15
                                                             isSizetoFit:NO
                                                           textAlignment:NSTextAlignmentLeft];
            stoneobs_ui_label.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:15];
            [header addSubview:stoneobs_ui_label];
            top = stoneobs_ui_label.bottom;
            CGFloat temptop = top;
            for (NSInteger i = 0 ;i < model.subs.count;i ++) {
                THCateModel * subModel = model.subs[i];
                STTools_MenuControl * menuControl = [[STTools_MenuControl alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 130) imageName:@"" title:subModel.name titleColor:STONEOBS_UI_FIRST_TEXT_COLOR imageHeight:80 lableHeight:40];
                [menuControl setOnSelctedControl:^(STTools_MenuControl *control) {
                    
                    THCateDetailViewController * vc = THCateDetailViewController.new;
                    vc.c_id = subModel.c_id;
                    [weakSelf pushViewController:vc animated:1];
                }];
                menuControl.top = temptop + menuControl.height * (i/3);
                menuControl.left = buttonWith * (i%3);
                header.height = menuControl.bottom;
                [menuControl.imageButton sd_setImageWithURL:subModel.icon.mj_url forState:UIControlStateNormal];;
                [header addSubview:menuControl];
                top = menuControl.bottom;
            }
            
        }
    }
    
    

    header.height = top + 30;
    NSLog(@"%ld",model.subs.count);
    self.tableView.tableHeaderView = header;
    [self.tableView reloadData];
    
    MJRefreshFooter * footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footer_action];
    }];

    self.tableView.mj_footer = footer;
    [self.tableView reloadData];
    self.tableView.contentInset = UIEdgeInsetsZero;

}
- (void)footer_action{

    [self.tableView.mj_footer endRefreshing];
    self.tableView.mj_footer = nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSInteger index = [self.dataSouce indexOfObject:self.chosedModel];
        index = index + 1;
        if (index >= self.dataSouce.count) {
            index = 0;
        }
        
        for (NSInteger i = 0; i < self.controlArray.count; i ++) {
            THCategoryControl * existControl = self.controlArray[i];
            existControl.selected = NO;
            if (i == index) {
                existControl.selected = YES;
            }
        }
        self.chosedModel = self.dataSouce[index];
        [self config_seg_view];
        [self.tableView setContentOffset:CGPointZero animated:NO];
    });
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //活动
    return;
    CGFloat y = scrollView.contentOffset.y;
    CGFloat max_y = self.tableView.tableHeaderView.height - self.tableView.height;
    if (y >= max_y) {
        //选择
        NSInteger index = [self.dataSouce indexOfObject:self.chosedModel];
        index = index + 1;
        if (index >= self.dataSouce.count) {
            index = 0;
        }
        
        for (NSInteger i = 0; i < self.controlArray.count; i ++) {
            THCategoryControl * existControl = self.controlArray[i];
            existControl.selected = NO;
            if (i == index) {
                existControl.selected = YES;
            }
        }
        self.chosedModel = self.dataSouce[index];
        [self config_seg_view];
    }
}
#pragma mark --stoneobs_net netWork Method
- (void)send_all_cate_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/goods/getAllCate"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSArray * data = [responseObject valueForKey:@"data"];
        NSArray * cates = [THCateModel mj_objectArrayWithKeyValuesArray:data];
        self.dataSouce = cates.mutableCopy;
        [self configSubView];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
